package org.jader.bolao.statistics;

import java.util.Iterator;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import org.jader.bolao.ClassificationAlgorithm;
import org.jader.bolao.Game;
import org.jader.bolao.Team;
import org.jader.bolao.classificationalgorithm.ClassifyByPoints;
import org.jader.bolao.classificationalgorithm.ClassifyByTotals;
import org.jader.bolao.classificationalgorithm.ClassifyByWins;
import org.jader.bolao.statistics.classificationtable.TeamRow;
import org.jader.bolao.statistics.classificationtable.TeamRowByPoints;
import org.jader.bolao.statistics.classificationtable.TeamRowByTotals;
import org.jader.bolao.statistics.classificationtable.TeamRowByWins;

public class ClassificationTable {
	private SortedSet<TeamRow> rows = new TreeSet<TeamRow>();
	private ClassificationAlgorithm ca = null;
	
	public ClassificationTable(ClassificationAlgorithm ca, Set<Game> games) {
		this.ca = ca;
		// Generate table rows organized by ClassificationAlgorithm
		Iterator<Team> it = ca.classifyBy(games).iterator();
		while (it.hasNext()) {
			Team team = it.next();
			// Create customized TeamRow based on Classification Algorithm
			if (ca instanceof ClassifyByPoints) {
				rows.add(new TeamRowByPoints(this, team, games));
			}
			else if (ca instanceof ClassifyByTotals) {
				rows.add(new TeamRowByTotals(this, team, games));
			}
			else if (ca instanceof ClassifyByWins) {
				rows.add(new TeamRowByWins(this, team, games));
			}
		}
	}
	
	public ClassificationAlgorithm getClassificationAlgorithm() {return this.ca;}

	public int getTeamPosition(Team t) {
		int position = 0;
		int teamTotal = -1;
		float teamPoints = -1;
		Iterator<TeamRow> it = rowsIterator();
		while (it.hasNext() && teamTotal < 0) {
			TeamRow tr = it.next();
			if (tr.team().equals(t)) {
				teamTotal = tr.getTotalColumn().totalSum();
				if (tr instanceof TeamRowByPoints) {
					teamPoints = ((TeamRowByPoints) tr).getTotalColumn().points();
				}
			}
		}
		it = rowsIterator();
		while (it.hasNext()) {
			position++;
			TeamRow tr = it.next();
			if (tr instanceof TeamRowByPoints) {
				TeamRowByPoints trp = (TeamRowByPoints) tr;
				if (trp.getTotalColumn().points() == teamPoints)
					return position;
			}
			else
				if (tr.getTotalColumn().totalSum() == teamTotal)
					return position;
		}
		return -1;
	}
	
	public Iterator<TeamRow> rowsIterator() {
		return this.rows.iterator();
	}
	
	public TeamRow firstRow() {
		return this.rows.first();
	}

	public int getRowCount() {
		return this.rows.size();
	}

	public TeamRow getRow(int row) {
		return (TeamRow) rows.toArray()[row];
	}
}
